const db = require('../db');

exports.getList = async (ctx) => {
  const { page = 1, pageSize = 10, nickname = '', role = '' } = ctx.query;
  const offset = (page - 1) * pageSize;
  const where = [];
  const params = [];

  if (nickname) {
    where.push('nickname LIKE ?');
    params.push(`%${nickname}%`);
  }
  if (role && ['好大哥', '好大姐'].includes(role)) {
    where.push('role = ?');
    params.push(role);
  }

  const whereClause = where.length ? `WHERE ${where.join(' AND ')}` : '';
  console.log(whereClause,'whereClause');
  
  try {
    const [data] = await db.query(
      `SELECT * FROM warming ${whereClause} LIMIT ?, ?`,
      [...params, parseInt(offset), parseInt(pageSize)]
    );

    const [countRows] = await db.query(
      `SELECT COUNT(*) as total FROM warming ${whereClause}`,
      params
    );

    ctx.body = {
      code: 200,
      data,
      pagination: {
        total: countRows[0].total,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    };
  } catch (err) {
    console.log(err,'err');
    
    ctx.body = { code: 500, message: err.message };
  }
};

exports.addItem = async (ctx) => {
  const { nickname, role, giftName, total, leftCount } = ctx.request.body;
  if (!nickname || !role || !giftName || total == null || leftCount == null) {
    ctx.status = 400;
    ctx.body = { message: '参数缺失' };
    return;
  }

  try {
    const [res] = await db.query(
      'INSERT INTO warming (nickname, role, giftName, total, leftCount) VALUES (?, ?, ?, ?, ?)',
      [nickname, role, giftName, total, leftCount]
    );
    ctx.body = { code: 200, message: '添加成功', id: res.insertId };
  } catch (err) {
    ctx.body = { code: 500, message: err.message };
  }
};

exports.updateItem = async (ctx) => {
  const { id } = ctx.params;
  const { nickname, role, giftName, total, leftCount } = ctx.request.body;
  try {
    await db.query(
      'UPDATE warming SET nickname=?, role=?, giftName=?, total=?, leftCount=? WHERE id=?',
      [nickname, role, giftName, total, leftCount, id]
    );
    ctx.body = { code: 200, message: '更新成功' };
  } catch (err) {
    ctx.body = { code: 500, message: err.message };
  }
};

exports.deleteItem = async (ctx) => {
  const { id } = ctx.params;
  try {
    await db.query('DELETE FROM warming WHERE id = ?', [id]);
    ctx.body = { code: 200, message: '删除成功' };
  } catch (err) {
    ctx.body = { code: 500, message: err.message };
  }
};
